﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BookShop.BLL;
using BookShop.DTO;
using BookShop.Library.Common;
using BookShop.Library.Constant;
using BookShop.Site.Models;
using PagedList;

namespace BookShop.Site.Controllers
{
    public class BookController : Controller
    {
        public ActionResult Detail(int bookId)
        {
            var book = BookService.GetById(bookId);
            var model = new HomeViewModel
            {
                CategoryList = CategoryService.GetAll(),
                BestSellerBookList = BookService.UpdateNotMappedField(BookService.GetBestSellers(10, TimePeriod.Month)),
                HasPriceSlider = false

            };
            if (book.Status == BookStatus.Inactive)
            {
                book = null;
            }
            if (book != null)
            {
                book = BookService.UpdateNotMappedField(new List<Book> { book }).FirstOrDefault();
                if (book != null)
                {
                    model.DetailBook = book;
                    model.SameAuthorBookList = BookService.UpdateNotMappedField(BookService.GetByAuthorId(book.AuthorId));
                    model.SameAuthorBookList.Remove(book);
                }
            }
            return View(model);
        }

        [ValidateInput(false)]
        public ActionResult RateComment(long bookId, long customerId, string review, string ratePoint)
        {
            var book = BookService.GetById(bookId);
            var customer = CustomerService.GetById(customerId);
            if (book != null && customer != null)
            {
                var rateComment = new RateComment
                {
                    CustomerId = customerId,
                    BookId = bookId,
                    Status = RateCommentStatus.Active,
                    CreateTime = DateTime.Now,
                    CommentContent = review,
                    BookTitle = book.Title,
                    CustomerName = customer.FullName
                };
                double dRatePoint;
                var isValidRatePoint = double.TryParse(ratePoint, NumberStyles.AllowDecimalPoint,
                    CultureInfo.CreateSpecificCulture("en-US"), out dRatePoint);
                if (isValidRatePoint)
                {
                    rateComment.RatePoint = dRatePoint;
                }
                RateCommentService.Add(rateComment);
                BookService.UpdateAverageRatePoint(bookId);
            }
            return RedirectToAction("Detail", new { bookId });
        }
    }
}
